﻿import random
from simcell.cell.cell import Cell

class Organism:
  id = 0
  
  def __init__(self, world):
    Organism.id = Organism.id + 1
    self.id = Organism.id
    self.world = world
    self.cells = []
    self.pos = 0, 0
  
  def __str__(self):
    return "Organism %d" % self.id
    
  def info(self):
    info = []
    info.append(str(self))
    
    info_cells = []
    for cell in self.cells:
      info_cell = map(lambda x: "  " + x, cell.info())
      info.extend(info_cell)
      
    return info
    
  def cicle(self):
    new_cells = []
    for cell in self.cells:
      c = cell.cicle()
      if not c is None:
        new_cells.append(c)
        
    if len(new_cells) > 0:
        for cell in new_cells:
            organism = Organism(self.world)
            organism.pos = self.pos
            organism.cells = [cell]
            organism.world.appendorganism(organism)
      
  def selectRandomCell(self):
    i = random.randint(0, len(self.cells) - 1)
    return self.cells[i]
    
  def move(self):
    x_offset = float(1 - random.randint(0,2)) / len(self.cells)
    y_offset = float(1 - random.randint(0,2)) / len(self.cells)
    
    x, y = self.pos    
    x += x_offset / len(self.cells)
    y += y_offset / len(self.cells)
    
    if x < 0:
      x = self.world.maxX
    if x > self.world.maxX:
      x = 0
    if y < 0:
      y = self.world.maxY
    if y > self.world.maxY:
      y = 0
    
    self.pos = x, y
    
  def getJoints(self):
    joints = {}
    for cell in self.cells:
      cjoints = cell.getJoints();
      if not cjoints is None:
        for k, v in cjoints.iteritems():
          if joints.has_key(k):          
            n = joints[k]
            joints[k] = max(n, v) - min(n, v)
          else:
            joints[k] = cjoints[k]
        
    return joints
